package cn.pconline.autoclub.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.Mid;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.Subject;
import cn.pconline.autoclub.entity.SubjectDyna;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;

/**
 * 
 * @author zhoutianhuai
 *
 * 2015年3月27日 下午6:11:28
 */
public class SubjectDynaService {

    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private PagerService pagerService;
    
    private static final Logger log = LoggerFactory.getLogger(SubjectDynaService.class);
   /**
    * 创建话题动态
    * @param subjectDyna
    * @return
    */
    public long createSubjectDyna(SubjectDyna subjectDyna) {
        return geliDao.create(subjectDyna);
    }
    
	/**
	 * 创建动态话题分表
	 * @param subject
	 * @param dynaInfoId
	 * @param isTop  （注意字段由是否主话题转为是否置顶）
	 */
	public void createDynaSubject(Subject subject,long dynaInfoId,int isTop){
		SubjectDyna subjectDyna = new SubjectDyna();
		subjectDyna.setSubjectId( subject.getSubjectId());
		subjectDyna.setDynaInfoId(dynaInfoId);
		subjectDyna.setIsTop( isTop );
		subjectDyna.setCreateAt(subject.getCreateAt());
		subjectDyna.setCreateBy( subject.getCreateBy());
		subjectDyna.setStatus( subject.getStatus());
		geliDao.create( subjectDyna );
	}
	
	/**
	 * 查找话题动态
	 * @param subjectId
	 * @param dynaInfoId
	 * @return
	 */
	public SubjectDyna findSubjectDynaById(long subjectId,long dynaInfoId){
		try {
			return geliDao.find( SubjectDyna.class, subjectId, new Mid(subjectId,dynaInfoId));
        }
        catch( EmptyResultDataAccessException e ) {
        	log.warn("cant't find subjectDyna which subjectId:{},dynaInfoId:{}",subjectId,dynaInfoId);
	        return null;
        }
	}
	
	
	public long updateByField(SubjectDyna subjectDyna,String fields){
		return geliDao.update( subjectDyna, fields );
	}
    
    /**
     * 逻辑删除主题动态
     * @param subjectId
     * @param dynaInfoId
     * @return
     */
    public long deleteSubjectDyna(long subjectId, long dynaInfoId) {
        try {
            SubjectDyna subjectDyna = geliDao.find(SubjectDyna.class,subjectId, new Mid(subjectId,dynaInfoId));
            if(subjectDyna==null || subjectDyna.getStatus() == SubjectDyna.STATUS_DELETE) return 0;
            subjectDyna.setStatus(SubjectDyna.STATUS_DELETE);
            return geliDao.update(subjectDyna, "status");
        } catch (EmptyResultDataAccessException e) {
            return 0;
        }
    }
    
    /**
     * 更新置顶字段
     * @param subjectDyna
     * @param isTop
     * @return
     */
    public int updateTop(long subjectId, long dynaInfoId,int isTop){
    	try {
    		SubjectDyna subjectDyna = geliDao.find(SubjectDyna.class,subjectId, new Mid(subjectId,dynaInfoId));
            if(subjectDyna==null || subjectDyna.getStatus() == SubjectDyna.STATUS_DELETE) return 0;
        	subjectDyna.setIsTop( isTop );
        	subjectDyna.setTopDate(DateUtils.getNow());
        	return geliDao.update(subjectDyna, "is_top,top_date");
        }
        catch( EmptyResultDataAccessException e ) {
        	 return 0;
        }
    }
    
	/**
	 * 根据subjectid查找相关的话题动态（按发表时间倒序）
	 * @param subjectId
	 * @param pageNo
	 * @param pageSize
	 * @param type  1:只查询置顶，  0：只查询不置顶的 ，2：全部查询
	 * @return
	 */
	public Pager<DynaInfo> pageDynaBySubjectIdOrderNew(long subjectId,int pageNo, int pageSize,int type){
		SqlBuilder sql = new SqlBuilder();
		String selectSql = "select dyna_info_id,create_at ";
		sql.appendSql("select dyna_info_id,create_at from ").appendSql(geliOrm.getTableName(SubjectDyna.class, subjectId ))
			.appendSql(" where status = ").appendValue(Subject.STATUS_NORMAL)
			.appendSql(" and subject_id = ").appendValue(subjectId);
		if(type==Subject.TOP_YES){
			sql.appendSql(" and is_top = ").appendValue(Subject.TOP_YES);
		}else if(type == Subject.TOP_NO){
			sql.appendSql(" and is_top = ").appendValue(Subject.TOP_NO);
		}
		String orderSql = " order by create_at desc ";
		return subjectService.getDynaListBySql(sql,orderSql,selectSql,pageNo,pageSize);
	}
	
	/**
	 * 根据subjectid查找相关的话题动态（按动态的回复数量倒序）
	 * @param subjectId
	 * @param pageNo
	 * @param pageSize
	 * @param type  1:只查询置顶，  0：只查询不置顶的 ，2：全部查询
	 * @return
	 */
	public Pager<DynaInfo> pageDynaBySubjectIdOrderReply(long subjectId,int pageNo, int pageSize,int type){
		SqlBuilder sql = new SqlBuilder();
		String selectSql = "select dyna_info_id,create_at ";
		sql.appendSql("select dyna_info_id,create_at from ").appendSql(geliOrm.getTableName(SubjectDyna.class, subjectId ))
			.appendSql(" where status = ").appendValue(Subject.STATUS_NORMAL)
			.appendSql(" and subject_id = ").appendValue(subjectId);
		if(type==Subject.TOP_YES){
			sql.appendSql(" and is_top = ").appendValue(Subject.TOP_YES);
		}else if(type == Subject.TOP_NO){
			sql.appendSql(" and is_top = ").appendValue(Subject.TOP_NO);
		}
		String orderSql = " order by post_count desc,create_at desc ";
		return subjectService.getDynaListBySql(sql,orderSql,selectSql,pageNo,pageSize);
	}
	
	/**
	 * 查询置顶动态
	 * @param subjectId
	 * @return
	 */
	public List<DynaInfo> listDynaByTop(long subjectId){
		SqlBuilder sql = new SqlBuilder();
		sql.appendSql("select dyna_info_id,create_at from ").appendSql(geliOrm.getTableName(SubjectDyna.class, subjectId ))
			.appendSql(" where status = ").appendValue(Subject.STATUS_NORMAL)
			.appendSql(" and subject_id = ").appendValue(subjectId);
		sql.appendSql(" and is_top = ").appendValue(Subject.TOP_YES);
		String orderSql = " order by top_date desc ";
		return subjectService.listDynaListBySql( sql, orderSql );
	}
	
	 /**
     * 根据用户id列举所属用户参与过的话题按时间倒序
     * @param userId
     * @return
     */
    public List<User> listUserBySubjectId(long subjectId, int pageSize){
    	SqlBuilder sql = new SqlBuilder();
    	sql.appendSql("select distinct create_by from ").appendSql(geliOrm.getTableName(SubjectDyna.class, subjectId))
			.appendSql(" where status = ").appendValue(Subject.STATUS_NORMAL)
			.appendSql(" and subject_id = ").appendValue(subjectId)
			.appendSql(" order by create_at desc ");
    	List<Long> idList =jdbcTemplate.query(sql.getSql(), sql.getValues(), new ResultSetExtractor<List<Long>>(){
			@Override
            public List<Long> extractData( ResultSet rs ) throws SQLException, DataAccessException {
				List<Long> list = new ArrayList<Long>();
	            while (rs.next()) {
                    long create_by = rs.getLong("create_by");
                    list.add( create_by);
                }
	            return list;
            }
    		
    	});
    	if(idList == null || idList.size() == 0){
    		return null;
    	}
    	try {
    		List<User> list = new ArrayList<User>();
    		int count = 0;
    		for(Long userId : idList){
    			User user = userService.authUser(userId);
    			if(user != null){
    				count++;
    				list.add(user);
    			}
    			if(count == pageSize){
    				break;
    			}
    		}
	        return list;
        }
        catch( EmptyResultDataAccessException e ) {
        	log.warn("The subjectId {} can't find top {} user which userIds in {}", subjectId, pageSize, idList.toString());
        	return Collections.emptyList();
        }
    	
    } 
          /**
         * 计算ID列表里不同话题个数
         * @param ids
         * @return 
         */
	public int countSubjectDyna(String ids) {
		if (StringUtils.isBlank(ids))
			return 0;
		HashSet<String> set = new HashSet<String>();
		String[] id = ids.split(",");
		for (String s : id) {
			set.add(s);
		}
		return set.size();
	}
	
	/**
	 * 根据subjectid查找相关的话题动态（按发表时间倒序）-- 专门提供给上海车展2015的
	 * @param subjectId
	 * @param pageNo
	 * @param pageSize
	 * @param type  1:只查询置顶，  0：只查询不置顶的 ，2：全部查询
	 * @return
	 */
	public Pager<DynaInfo> pageDynaByShangHai2015(long subjectId,int pageNo, int pageSize,int type){
		SqlBuilder sql = new SqlBuilder();
		String selectSql = "select dyna_info_id,create_at ";
		sql.appendSql("select dyna_info_id,create_at from ").appendSql(geliOrm.getTableName(SubjectDyna.class, subjectId ))
			.appendSql(" where status = ").appendValue(Subject.STATUS_NORMAL)
			.appendSql(" and subject_id = ").appendValue(subjectId);
		if(type==Subject.TOP_YES){
			sql.appendSql(" and is_top = ").appendValue(Subject.TOP_YES);
		}else if(type == Subject.TOP_NO){
			sql.appendSql(" and is_top = ").appendValue(Subject.TOP_NO);
		}
		 String orderSql = " order by create_at desc ";
		 return subjectService.getDynaListByShangHai2015(sql,orderSql,selectSql,pageNo,pageSize);
	}
	
	/**
	 * 根据subjectid查找相关的话题动态（按发表时间倒序）
	 * @param subjectId
	 * @param pageNo
	 * @param pageSize
	 * @param type  1:只查询置顶，  0：只查询不置顶的 ，2：全部查询
	 * @return
	 */
	public Pager<SubjectDyna> pageBySubjectIdCreateAt(long subjectId, int pageNo, int pageSize, int type){
		SqlBuilder sql = new SqlBuilder();
		sql.appendSql("select subject_id, dyna_info_id from ").appendSql(geliOrm.getTableName(SubjectDyna.class, subjectId))
			.appendSql(" where status = ").appendValue(Subject.STATUS_NORMAL)
			.appendSql(" and subject_id = ").appendValue(subjectId);
		if(type==Subject.TOP_YES){
			sql.appendSql(" and is_top = ").appendValue(Subject.TOP_YES);
		}else if(type == Subject.TOP_NO){
			sql.appendSql(" and is_top = ").appendValue(Subject.TOP_NO);
		}
		 sql.appendSql(" order by create_at desc ");
		 return pagerService.pager(SubjectDyna.class, subjectId, sql, pageNo, pageSize);
	}
	
	/**
	 * 根据subjectid查找相关的话题动态（按评论数倒序）
	 * @param subjectId
	 * @param pageNo
	 * @param pageSize
	 * @param type  1:只查询置顶，  0：只查询不置顶的 ，2：全部查询
	 * @return
	 */
	public Pager<SubjectDyna> pageBySubjectIdPostCount(long subjectId, int pageNo, int pageSize, int type){
		SqlBuilder sql = new SqlBuilder();
		sql.appendSql("select subject_id, dyna_info_id from ").appendSql(geliOrm.getTableName(SubjectDyna.class, subjectId))
			.appendSql(" where status = ").appendValue(Subject.STATUS_NORMAL)
			.appendSql(" and subject_id = ").appendValue(subjectId);
		if(type==Subject.TOP_YES){
			sql.appendSql(" and is_top = ").appendValue(Subject.TOP_YES);
		}else if(type == Subject.TOP_NO){
			sql.appendSql(" and is_top = ").appendValue(Subject.TOP_NO);
		}
		 sql.appendSql(" order by post_count desc ");
		 return pagerService.pager(SubjectDyna.class, subjectId, sql, pageNo, pageSize);
	}
}
